package com.ygr.anime.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ygr.anime.domain.User;
import com.ygr.anime.dto.LoginDto;
import com.ygr.anime.dto.RegisterDto;
import com.ygr.anime.dto.UserDto;
import com.ygr.anime.exception.MyException;
import com.ygr.anime.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@RestController
@AllArgsConstructor
@SaIgnore
class AuthController {

    private final UserService userService;

    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }

    @PostMapping("/login")
    public SaResult login(@RequestBody LoginDto login) {
        User user = userService.getOne(
                new LambdaQueryWrapper<User>().eq(User::getName, login.username())
        );
        if (user == null) {
            throw new MyException("用户名不存在");
        }

        if (!(login.username().equals(user.getName()) && login.password().equals(user.getPassword()))) {
            throw new MyException("用户名或密码错误");
        }

        StpUtil.login(user.getId());

        UserDto userDto = new UserDto(user.getId(),
                user.getName(),
                user.getNickname(),
                user.getAvatar(),
                StpUtil.getRoleList()
        );

        return SaResult.ok("登录成功").setData(userDto);
    }

    @PostMapping("/register")
    public SaResult register(@RequestBody RegisterDto register) {

        if (
                userService.getOne(
                        new LambdaQueryWrapper<User>().eq(User::getName, register.username())
                ) != null
        ) {
            throw new MyException("用户名已存在");
        }

        User user = User.builder()
                .name(register.username())
                .password(register.password())
                .nickname(register.username())
                .points(new BigDecimal(0))
                .isEnabled(true)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .build();

        boolean b = userService.save(user);
        if (!b) {
            throw new MyException("注册失败");
        }
        return SaResult.ok("注册成功");
    }

}
